//
//  XHDemoWeChatMessageTableViewController.m
//  MessageDisplayExample
//
//  Created by HUAJIE-1 on 14-4-27.
//  Copyright (c) 2014年 嗨，我是曾宪华(@xhzengAIB)，曾加入YY Inc.担任高级移动开发工程师，拍立秀App联合创始人，热衷于简洁、而富有理性的事物 QQ:543413507 主页:http://zengxianhua.com All rights reserved.
//

#import "XHDemoWeChatMessageTableViewController.h"

#import "XHDisplayTextViewController.h"
#import "XHDisplayMediaViewController.h"
#import "XHDisplayLocationViewController.h"

#import "XHAudioPlayerHelper.h"
#import "CWQXHMessage.h"
#import "WCCoreDataStore.h"
#import <objc/runtime.h>
#import "Conversation.h"
#import "WSJConversion.h"
#import "MJRefresh.h"
#import "Constants.h"
#import "NSDate+Category.h"
#import "WCDefaultManager.h"
#import "CWQIMNetManager.h"
#import "WSJObserveNewChatTool.h"
#import "Masonry.h"

//#import "SDPieLoopProgressView.h"

#define weixinMessageUrl @"https://api.weixin.qq.com/cgi-bin/media/upload"
#define  accessToken   @"9yslWWZYYkKd1Y7d_T-3_kzvN5QaDZw5wlvz-T816066SEuNRIc55yfnTI2chSlya1-wyKm5mqlTriFg0rWAlGOEk6SG1Svl9J9LoQ78e4g3XFRJ8iQIi9ZLyGTBKGD8SIIcAIAKAA"

@interface XHDemoWeChatMessageTableViewController () <XHAudioPlayerHelperDelegate>

@property (nonatomic, strong) NSArray *emotionManagers;

@property (nonatomic, strong) XHMessageTableViewCell *currentSelectedCell;
@property (nonatomic, assign) BOOL *moreOldData;
@property(nonatomic, strong)WSJConversion *conversion;
@property(nonatomic, strong)NSTimer *timer;
@property (nonatomic,  assign) NSInteger lastMessageId;


@property (nonatomic,  assign) NSInteger currentRevealMessages;


@end

@implementation XHDemoWeChatMessageTableViewController


#pragma  mark --------------------接收消息------------------------------------
// 文本
- (XHMessage *)getTextMessage:(CWQXHMessage *)message{
    XHMessage *textMessage = [[XHMessage alloc] initWithText:message.text sender:message.sender timestamp:message.timestamp];
    textMessage.avatar = [UIImage imageNamed:@"avatar"];
    textMessage.avatarUrl = @"http://www.pailixiu.com/jack/meIcon@2x.png";
    textMessage.bubbleMessageType = [message.bubbleMessageType integerValue];
    textMessage.isSending = NO;
    textMessage.completedSend = YES;
    return textMessage;
}

// 照片
- (XHMessage *)getPhotoMessage:(CWQXHMessage *)message {
    XHMessage *photoMessage = [[XHMessage alloc] initWithPhoto:message.photo thumbnailUrl:message.thumbnailUrl originPhotoUrl:message.originPhotoUrl sender:message.sender timestamp:message.timestamp];
    photoMessage.avatar = [UIImage imageNamed:@"avatar"];
    photoMessage.avatarUrl = @"http://www.pailixiu.com/jack/JieIcon@2x.png";
    photoMessage.bubbleMessageType = [message.bubbleMessageType integerValue];
    photoMessage.isSending = NO;
    photoMessage.completedSend = YES;
    return photoMessage;
}

// 视频
- (XHMessage *)getVideoMessage:(CWQXHMessage *)message {
//    NSString *videoPath = [[NSBundle mainBundle] pathForResource:@"IMG_1555.MOV" ofType:@""];
    XHMessage *videoMessage = [[XHMessage alloc] initWithVideoConverPhoto:message.videoConverPhoto videoPath:message.videoPath videoUrl:message.videoUrl sender:message.sender timestamp:message.timestamp];
    videoMessage.avatar = [UIImage imageNamed:@"avatar"];
    videoMessage.isRead = [message.isRead boolValue];
    videoMessage.avatarUrl = @"http://www.pailixiu.com/jack/JieIcon@2x.png";
    videoMessage.bubbleMessageType = [message.bubbleMessageType integerValue];
    videoMessage.isSending = NO;
    videoMessage.completedSend = YES;

    return videoMessage;
}
// 音频
- (XHMessage *)getVoiceMessage:(CWQXHMessage *)message {
    XHMessage *voiceMessage = [[XHMessage alloc] initWithVoicePath:message.voicePath voiceUrl:message.voiceUrl voiceDuration:message.voiceDuration sender:message.sender timestamp:message.timestamp isRead:[message.isRead boolValue]];
    voiceMessage.avatar = [UIImage imageNamed:@"avatar"];
    voiceMessage.avatarUrl = @"http://www.pailixiu.com/jack/JieIcon@2x.png";
    voiceMessage.bubbleMessageType = [message.bubbleMessageType integerValue];
    voiceMessage.completedSend = YES;

    return voiceMessage;
}
// 表情
- (XHMessage *)getEmotionMessage:(CWQXHMessage *)message {
    XHMessage *emotionMessage = [[XHMessage alloc] initWithEmotionPath:message.emotionPath sender:message.sender timestamp:message.timestamp];
    emotionMessage.avatar = [UIImage imageNamed:@"avatar"];
    emotionMessage.avatarUrl = @"http://www.pailixiu.com/jack/JieIcon@2x.png";
    emotionMessage.bubbleMessageType = [message.bubbleMessageType integerValue];
    emotionMessage.completedSend = YES;

    return emotionMessage;
}

// 位置
- (XHMessage *)getGeolocationsMessage:(CWQXHMessage *)message {
    XHMessage *localPositionMessage = [[XHMessage alloc] initWithLocalPositionPhoto:message.localPositionPhoto geolocations:message.geolocations location:[[CLLocation alloc] initWithLatitude:23.110387 longitude:113.399444] sender:@"Jack" timestamp:[NSDate date]];
    localPositionMessage.avatar = [UIImage imageNamed:@"avatar"];
    localPositionMessage.avatarUrl = @"http://www.pailixiu.com/jack/meIcon@2x.png";
    localPositionMessage.bubbleMessageType = [message.bubbleMessageType integerValue];
    
    return localPositionMessage;
}


- (void)receiveNewMessageNot:(NSNotification *)not{
    NSArray *arr = not.userInfo[@"ConversionAndMessage"];
    
  
    XHMessage *message =arr[1];
    if (message.conversionId == self.conversion.rowid) {
        [self addMessage:message];
    }
    
    
  
  
}




#pragma mark -从数据库分页获取查询
- (NSArray *)getTestMessages {
    
    
    
//    _chaterInfo
    LKDBHelper *db =  [XHMessage getUsingLKDBHelper];
    NSString *sql;
    NSString *tableName =[XHMessage getTableName];
    if (self.lastMessageId <=0) {
        sql =[NSString stringWithFormat:@"select * from %@ where conversionId = %d order by rowid desc limit 0,12",tableName,self.conversion.rowid];
    }else{
         sql =[NSString stringWithFormat:@"select * from %@ where conversionId = %d and rowid < %d order by rowid desc limit 0,12",tableName,self.conversion.rowid,self.lastMessageId];
       
    }
       NSArray *results =[db searchWithRAWSQL:sql toClass:[XHMessage class]];
    if (results.count>0) {
        NSLog(@"");
        XHMessage *m = results.lastObject;
        self.lastMessageId =m.rowid;
        NSLog(@"最后一条(最小一条)%d",self.lastMessageId);
    }
    //倒序
    return [[results reverseObjectEnumerator] allObjects];

}
#pragma mark - Message Calculate Cell Height

- (CGFloat)calculateCellHeightWithMessage:(id <XHMessageModel>)message atIndexPath:(NSIndexPath *)indexPath {
    CGFloat cellHeight = 0;
    
    BOOL displayTimestamp = YES;
    if ([self.delegate respondsToSelector:@selector(shouldDisplayTimestampForRowAtIndexPath:)]) {
        displayTimestamp = [self.delegate shouldDisplayTimestampForRowAtIndexPath:indexPath];
    }
    
    cellHeight = [XHMessageTableViewCell calculateCellHeightWithMessage:message displaysTimestamp:displayTimestamp];
    
    return cellHeight;
}
#pragma mark -加载信息


static CGPoint  table_delayOffset = {0.0};
- (void)loadDemoDataSource {
    WEAKSELF
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        NSArray *oldMessages = [weakSelf getTestMessages];
        ;
        weakSelf.currentRevealMessages +=oldMessages.count;
//        ---------------------------
      
            table_delayOffset = weakSelf.messageTableView.contentOffset;
            NSMutableArray *indexPaths = [[NSMutableArray alloc] initWithCapacity:oldMessages.count];
            NSMutableIndexSet *indexSets = [[NSMutableIndexSet alloc] init];
            [oldMessages enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
                NSIndexPath *indexPath = [NSIndexPath indexPathForRow:idx inSection:0];
                [indexPaths addObject:indexPath];
                
                table_delayOffset.y += [weakSelf calculateCellHeightWithMessage:[oldMessages objectAtIndex:idx] atIndexPath:indexPath];
                [indexSets addIndex:idx];
            }];
            
            NSMutableArray *messages = [[NSMutableArray alloc] initWithArray:weakSelf.messages];
            [messages insertObjects:oldMessages atIndexes:indexSets];
            
            
        dispatch_async(dispatch_get_main_queue(), ^{
            [UIView setAnimationsEnabled:NO];
            weakSelf.messageTableView.userInteractionEnabled = NO;
            //[self.messageTableView beginUpdates];
            
            weakSelf.messages = messages;
            
            [weakSelf.messageTableView insertRowsAtIndexPaths:indexPaths withRowAnimation:UITableViewRowAnimationNone];
            
            //[self.messageTableView endUpdates];
            
            [UIView setAnimationsEnabled:YES];
            
            [weakSelf.messageTableView setContentOffset:table_delayOffset animated:NO];
            weakSelf.messageTableView.userInteractionEnabled = YES;
            
            [weakSelf.messageTableView.header endRefreshing];
            

        });
        
        
    
    });
 
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
//    [[WCCoreDataStore shareStore] saveData];
    [[XHAudioPlayerHelper shareInstance] stopAudio];
}

- (id)initWithChatInfo:(WSJConversion *)conversion {
    self = [super init];
    self.conversion = conversion;
    if (self) {
        
          [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(receiveNewMessageNot:) name:WechatNewMessageInforNotificaiton object:nil];
       
        // 配置输入框UI的样式
//        self.allowsSendVoice = NO;
//        self.allowsSendFace = NO;
//        self.allowsSendMultiMedia = NO;
    }
    return self;
}

- (void)viewDidDisappear:(BOOL)animated{
    [super viewDidDisappear:animated];
    self.conversion.unread = @0;
    [self.conversion saveToDB];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    _moreOldData = YES;
    
 
    // Do any additional setup after loading the view.
    if (CURRENT_SYS_VERSION >= 7.0) {
        self.navigationController.interactivePopGestureRecognizer.delaysTouchesBegan=NO;
    }
    
    defineWeakSelf;
    self.messageTableView.frame = CGRectMake(0, 0, kScreenWidth, kScreenHeight -49);
    [self.messageTableView addLegendHeaderWithRefreshingBlock:^{
        [weakSelf loadDemoDataSource];
    }];
//    self.title = NSLocalizedStringFromTable(@"Chat", @"MessageDisplayKitString", @"聊天");
    self.title = self.conversion.patientName;
    // Custom UI
//    [self setBackgroundColor:[UIColor clearColor]];
//    [self setBackgroundImage:[UIImage imageNamed:@"TableViewBackgroundImage"]];
    
   

#pragma -mark 利用护士或者患者 做做前缀来命名 senderId
    // 设置自身用户名
    
    self.messageSender = [NSString stringWithFormat:@"NURSE_%@",[[[WCDefaultManager shareMg]account] stringId]];
    
    // 添加第三方接入数据
    NSMutableArray *shareMenuItems = [NSMutableArray array];
    NSArray *plugIcons = @[@"sharemore_pic", @"sharemore_video"];
    NSArray *plugTitle = @[@"照片", @"拍摄"];
    
    for (NSString *plugIcon in plugIcons) {
        XHShareMenuItem *shareMenuItem = [[XHShareMenuItem alloc] initWithNormalIconImage:[UIImage imageNamed:plugIcon] title:[plugTitle objectAtIndex:[plugIcons indexOfObject:plugIcon]]];
        [shareMenuItems addObject:shareMenuItem];
    }
    
    NSMutableArray *emotionManagers = [NSMutableArray array];
    for (NSInteger i = 0; i < 10; i ++) {
        XHEmotionManager *emotionManager = [[XHEmotionManager alloc] init];
        emotionManager.emotionName = [NSString stringWithFormat:@"表情%ld", (long)i];
        NSMutableArray *emotions = [NSMutableArray array];
        for (NSInteger j = 0; j < 18; j ++) {
            XHEmotion *emotion = [[XHEmotion alloc] init];
            NSString *imageName = [NSString stringWithFormat:@"section%ld_emotion%ld", (long)i , (long)j % 16];
            emotion.emotionPath = [[NSBundle mainBundle] pathForResource:[NSString stringWithFormat:@"emotion%ld.gif", (long)j] ofType:@""];
            emotion.emotionConverPhoto = [UIImage imageNamed:imageName];
            [emotions addObject:emotion];
        }
        emotionManager.emotions = emotions;
        
        [emotionManagers addObject:emotionManager];
    }
    
    self.emotionManagers = emotionManagers;
    [self.emotionManagerView reloadData];
    
    self.shareMenuItems = shareMenuItems;
    [self.shareMenuView reloadData];
    
    [self loadDemoDataSource];

}




- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)dealloc {
    self.emotionManagers = nil;
    [self.timer invalidate];
    lastMessageDate =nil;
    _timer = nil;
    [[XHAudioPlayerHelper shareInstance] setDelegate:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}


/*
 [self removeMessageAtIndexPath:indexPath];
 [self insertOldMessages:self.messages];
 */

#pragma mark - XHMessageTableViewCell delegate

- (void)multiMediaMessageDidSelectedOnMessage:(XHMessage *)message atIndexPath:(NSIndexPath *)indexPath onMessageTableViewCell:(XHMessageTableViewCell *)messageTableViewCell {
    UIViewController *disPlayViewController;
    switch (message.messageMediaType) {
        case XHBubbleMessageMediaTypeVideo:
        case XHBubbleMessageMediaTypePhoto: {
            DLog(@"message : %@", message.photo);
            DLog(@"message : %@", message.videoConverPhoto);
            XHDisplayMediaViewController *messageDisplayTextView = [[XHDisplayMediaViewController alloc] init];
            messageDisplayTextView.message = message;
            disPlayViewController = messageDisplayTextView;
            break;
        }
            break;
        case XHBubbleMessageMediaTypeVoice: {
            DLog(@"message : %@", message.voicePath);
            
            // Mark the voice as read and hide the red dot.
            if (!message.isRead) {
                message.isRead = YES;
            }
            
            messageTableViewCell.messageBubbleView.voiceUnreadDotImageView.hidden = YES;
            
            [[XHAudioPlayerHelper shareInstance] setDelegate:(id<NSFileManagerDelegate>)self];
            if (_currentSelectedCell) {
                [_currentSelectedCell.messageBubbleView.animationVoiceImageView stopAnimating];
            }
            if (_currentSelectedCell == messageTableViewCell) {
                [messageTableViewCell.messageBubbleView.animationVoiceImageView stopAnimating];
                [[XHAudioPlayerHelper shareInstance] stopAudio];
                self.currentSelectedCell = nil;
            } else {
                self.currentSelectedCell = messageTableViewCell;
                [messageTableViewCell.messageBubbleView.animationVoiceImageView startAnimating];
                NSString *voicePath = [message voicePath];
                NSString *path = [voicePath substringFromIndex:[voicePath length]-34];
                [[XHAudioPlayerHelper shareInstance] managerAudioWithFileName:[NSHomeDirectory() stringByAppendingFormat:@"%@", path] toPlay:YES];
            }
            [message updateToDB];
            break;
        }
        case XHBubbleMessageMediaTypeEmotion:
            DLog(@"facePath : %@", message.emotionPath);
            break;
        case XHBubbleMessageMediaTypeLocalPosition: {
            DLog(@"facePath : %@", message.localPositionPhoto);
            XHDisplayLocationViewController *displayLocationViewController = [[XHDisplayLocationViewController alloc] init];
            displayLocationViewController.message = message;
            disPlayViewController = displayLocationViewController;
            break;
        }
        default:
            break;
    }
    if (disPlayViewController) {
        [self.navigationController pushViewController:disPlayViewController animated:YES];
    }
}


- (void)didDoubleSelectedOnTextMessage:(id<XHMessageModel>)message atIndexPath:(NSIndexPath *)indexPath {
    DLog(@"text : %@", message.text);
    XHDisplayTextViewController *displayTextViewController = [[XHDisplayTextViewController alloc] init];
    displayTextViewController.message = message;
    [self.navigationController pushViewController:displayTextViewController animated:YES];
}

- (void)didSelectedAvatarOnMessage:(id<XHMessageModel>)message atIndexPath:(NSIndexPath *)indexPath {
    DLog(@"indexPath : %@", indexPath);
//    XHContact *contact = [[XHContact alloc] init];
//    contact.contactName = [message sender];
//    contact.contactIntroduction = @"自定义描述，这个需要和业务逻辑挂钩";
//    XHContactDetailTableViewController *contactDetailTableViewController = [[XHContactDetailTableViewController alloc] initWithContact:contact];
//    [self.navigationController pushViewController:contactDetailTableViewController animated:YES];
}

- (void)menuDidSelectedAtBubbleMessageMenuSelecteType:(XHBubbleMessageMenuSelecteType)bubbleMessageMenuSelecteType {
    
}

#pragma mark - XHAudioPlayerHelper Delegate

- (void)didAudioPlayerStopPlay:(AVAudioPlayer *)audioPlayer {
    if (!_currentSelectedCell) {
        return;
    }
    [_currentSelectedCell.messageBubbleView.animationVoiceImageView stopAnimating];
    self.currentSelectedCell = nil;
}

#pragma mark - XHEmotionManagerView DataSource

- (NSInteger)numberOfEmotionManagers {
    return self.emotionManagers.count;
}

- (XHEmotionManager *)emotionManagerForColumn:(NSInteger)column {
    return [self.emotionManagers objectAtIndex:column];
}

- (NSArray *)emotionManagersAtManager {
    return self.emotionManagers;
}

#pragma mark - XHMessageTableViewController Delegate



- (BOOL)shouldLoadMoreMessagesScrollToTop {
    return YES;
}

- (void)loadMoreMessagesScrollTotop {
//    
//    if (self.loadingMoreMessage ==YES) {
//        return;
//    }
//    
//    if (!self.loadingMoreMessage) {
//        self.loadingMoreMessage = YES;
//        
//        WEAKSELF
//        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
//            NSMutableArray *messages;
//            if (self.moreOldData) {
//                
//                messages = [weakSelf getTestMessages];
//            }
//            dispatch_async(dispatch_get_main_queue(), ^{
//                if ([messages count] > 0) {
//                    [weakSelf insertOldMessages:messages];
//                }
//                weakSelf.loadingMoreMessage = NO;
//            });
//        });
//    }
}

#pragma mark ---------------------------发送消息-------------------------------

/**
 *  发送文本消息的回调方法
 *
 *  @param text   目标文本字符串
 *  @param sender 发送者的名字
 *  @param date   发送时间
 */
- (void)didSendText:(NSString *)text fromSender:(NSString *)sender onDate:(NSDate *)date {
    XHMessage *textMessage = [[XHMessage alloc] initWithText:text sender:sender timestamp:date];
    textMessage.avatar = [UIImage imageNamed:@"Avatar"];
    textMessage.avatarUrl = @"http://www.pailixiu.com/jack/meIcon@2x.png";
    textMessage.completedSend = YES;
    textMessage.forignKey =self.conversion;
    
    textMessage.conversionId = self.conversion.rowid;
    
    //测试代码
//    [textMessage saveToDB];
//    [self addMessage:textMessage];
//    [self finishSendMessageWithBubbleMessageType:XHBubbleMessageMediaTypeText];
    
    defineWeakSelf;
    [[WSJObserveNewChatTool sharedObserveTool] sendAmessageToServerWithMessage:textMessage mediaId:nil thumbMediaId:nil complelte:^(id responseObject) {
        [textMessage saveToDB];
       
         [weakSelf addMessage:textMessage];
        [weakSelf finishSendMessageWithBubbleMessageType:XHBubbleMessageMediaTypeText];

    } fail:^(id errmesg) {
        
    }];
    
    
//    CWQXHMessage *entity = [NSEntityDescription insertNewObjectForEntityForName:@"CWQXHMessage" inManagedObjectContext:[WCCoreDataStore shareStore].context];
//    entity.text = text;
//    entity.sender = sender;
//    entity.timestamp = date;
//    self.chaterInfo.timestamp = date;
//    self.chaterInfo.detailText = text;
//    entity.conversation = self.chaterInfo;
//    entity.bubbleMessageType = XHBubbleMessageTypeSending;
//     entity.messageMediaType = [NSNumber numberWithInteger:XHBubbleMessageMediaTypeText];
//    [self dataBaseInsertNewObject:textMessage];
   
}


- (void)dataBaseInsertNewObject:(XHMessage *)message {

    /*
    NSManagedObject *entity = [NSEntityDescription insertNewObjectForEntityForName:@"CWQXHMessage" inManagedObjectContext:[WCCoreDataStore shareStore].context];
    
    [entity setValuesForKeysWithDictionary:(NSDictionary *)message];
     */
}




/**
 *  发送图片消息的回调方法
 *
 *  @param photo  目标图片对象，后续有可能会换
 *  @param sender 发送者的名字
 *  @param date   发送时间
 */
- (void)didSendPhoto:(UIImage *)photo fromSender:(NSString *)sender onDate:(NSDate *)date {
   
    XHMessage *photoMessage = [[XHMessage alloc] initWithPhoto:[UIImage imageWithData:UIImageJPEGRepresentation(photo, .45)] thumbnailUrl:nil originPhotoUrl:nil sender:sender timestamp:date];
    photoMessage.avatar = [UIImage imageNamed:@"avatar"];
//    photoMessage.avatarUrl = @"http://www.pailixiu.com/jack/meIcon@2x.png";
    photoMessage.isSending = YES;
    photoMessage.completedSend = YES;
     photoMessage.conversionId = self.conversion.rowid;
    [photoMessage saveToDB];
    [self addMessage:photoMessage];
   
//    CWQXHMessage *entity = [NSEntityDescription insertNewObjectForEntityForName:@"CWQXHMessage" inManagedObjectContext:[WCCoreDataStore shareStore].context];
//    entity.photo = photo;
//    entity.sender = sender;
//    entity.timestamp = date;
//    self.chaterInfo.timestamp = date;
//    self.chaterInfo.detailText = @"发送了一张图片";
//    entity.conversation = self.chaterInfo;
//    entity.bubbleMessageType = XHBubbleMessageTypeSending;
//    entity.messageMediaType = [NSNumber numberWithInteger:XHBubbleMessageMediaTypePhoto];
//    [self dataBaseInsertNewObject:photoMessage];
    [self finishSendMessageWithBubbleMessageType:XHBubbleMessageMediaTypePhoto];
    
}

/**
 *  发送视频消息的回调方法
 *
 *  @param videoPath 目标视频本地路径
 *  @param sender    发送者的名字
 *  @param date      发送时间
 */
- (void)didSendVideoConverPhoto:(UIImage *)videoConverPhoto videoPath:(NSString *)videoPath fromSender:(NSString *)sender onDate:(NSDate *)date {
    XHMessage *videoMessage = [[XHMessage alloc] initWithVideoConverPhoto:videoConverPhoto videoPath:videoPath videoUrl:nil sender:sender timestamp:date];
    videoMessage.avatar = [UIImage imageNamed:@"avatar"];
    videoMessage.avatarUrl = @"http://www.pailixiu.com/jack/meIcon@2x.png";
    videoMessage.isSending = YES;
    videoMessage.completedSend = YES;
    [self addMessage:videoMessage];
     self.currentRevealMessages +=1;
//    CWQXHMessage *entity = [NSEntityDescription insertNewObjectForEntityForName:@"CWQXHMessage" inManagedObjectContext:[WCCoreDataStore shareStore].context];
//    entity.videoConverPhoto = videoConverPhoto;
//    entity.videoPath = videoPath;
//    entity.sender = sender;
//    entity.timestamp = date;
//    self.chaterInfo.timestamp = date;
//    self.chaterInfo.detailText = @"发送了一段视频";
//    entity.conversation = self.chaterInfo;
//    entity.bubbleMessageType = XHBubbleMessageTypeSending;
//    entity.messageMediaType = [NSNumber numberWithInteger:XHBubbleMessageMediaTypeVideo];
//    [self dataBaseInsertNewObject:videoMessage];
    [self finishSendMessageWithBubbleMessageType:XHBubbleMessageMediaTypeVideo];
    
}

/**
 *  发送语音消息的回调方法
 *
 *  @param voicePath        目标语音本地路径
 *  @param voiceDuration    目标语音时长
 *  @param sender           发送者的名字
 *  @param date             发送时间
 */
- (void)didSendVoice:(NSString *)voicePath voiceDuration:(NSString *)voiceDuration fromSender:(NSString *)sender onDate:(NSDate *)date {
    XHMessage *voiceMessage = [[XHMessage alloc] initWithVoicePath:voicePath voiceUrl:nil voiceDuration:voiceDuration sender:sender timestamp:date];
    voiceMessage.avatar = [UIImage imageNamed:@"avatar"];
    voiceMessage.avatarUrl = @"http://www.pailixiu.com/jack/meIcon@2x.png";
    voiceMessage.isSending = YES;
    voiceMessage.completedSend = YES;
    [self addMessage:voiceMessage];
  

    [self finishSendMessageWithBubbleMessageType:XHBubbleMessageMediaTypeVoice];
   
}

/**
 *  发送第三方表情消息的回调方法
 *
 *  @param facePath 目标第三方表情的本地路径
 *  @param sender   发送者的名字
 *  @param date     发送时间
 */
- (void)didSendEmotion:(NSString *)emotionPath fromSender:(NSString *)sender onDate:(NSDate *)date {
    XHMessage *emotionMessage = [[XHMessage alloc] initWithEmotionPath:emotionPath sender:sender timestamp:date];
    emotionMessage.avatar = [UIImage imageNamed:@"avatar"];
    emotionMessage.avatarUrl = @"http://www.pailixiu.com/jack/meIcon@2x.png";
    emotionMessage.isSending = YES;
    emotionMessage.completedSend = YES;
    [self addMessage:emotionMessage];
//    CWQXHMessage *entity = [NSEntityDescription insertNewObjectForEntityForName:@"CWQXHMessage" inManagedObjectContext:[WCCoreDataStore shareStore].context];
//    entity.emotionPath = emotionPath;
//    entity.sender = sender;
//    entity.timestamp = date;
//    self.chaterInfo.timestamp = date;
//    entity.conversation = self.chaterInfo;
//    entity.bubbleMessageType = XHBubbleMessageTypeSending;
//    entity.messageMediaType = [NSNumber numberWithInteger:XHBubbleMessageMediaTypeEmotion];
//    [self dataBaseInsertNewObject:emotionMessage];
    [self finishSendMessageWithBubbleMessageType:XHBubbleMessageMediaTypeEmotion];
//    [self sendToWeixinWithMessage:emotionMessage indexPath:[NSIndexPath indexPathForRow:self.messages.count - 1 inSection:0]];

}

/**
 *  有些网友说需要发送地理位置，这个我暂时放一放
 */
- (void)didSendGeoLocationsPhoto:(UIImage *)geoLocationsPhoto geolocations:(NSString *)geolocations location:(CLLocation *)location fromSender:(NSString *)sender onDate:(NSDate *)date {
    XHMessage *geoLocationsMessage = [[XHMessage alloc] initWithLocalPositionPhoto:geoLocationsPhoto geolocations:geolocations location:location sender:sender timestamp:date];
    geoLocationsMessage.avatar = [UIImage imageNamed:@"avatar"];
    geoLocationsMessage.avatarUrl = @"http://www.pailixiu.com/jack/meIcon@2x.png";
    [self addMessage:geoLocationsMessage];
    
    [self dataBaseInsertNewObject:geoLocationsMessage];
    [self finishSendMessageWithBubbleMessageType:XHBubbleMessageMediaTypeLocalPosition];
}


#pragma mark －－－－－－－－－－网络请求－－－－－－－－－－－－－－

- (void)receiveMessageFromOurServer {
    
    [self receiveMediaFromWeixinWith:@{@"type":@"image" ,@"media_id":@"QRgkZCvcYGgYc2JiigRRi1qW2Dj2jGqco_inzEDbBHtXHf1AVduwRQi20Dzxyudc"} message:nil storeMessage:nil];
    

}





- (void)receiveMediaFromWeixinWith:(NSDictionary *)dict message:(XHMessage *)message storeMessage:(CWQXHMessage *)cwqXHMessage {
    
    
    weakSelf_define;
    
    /*
     * NSString *weixinGetMediaUrl = @"http://api.weixin.qq.com/cgi-bin/media/get";
     */
    NSString *weixinGetMediaUrl = @"https://api.weixin.qq.com/cgi-bin/media/get";
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    NSDictionary *param = @{@"access_token":accessToken ,@"media_id":dict[@"media_id"]};
    [manager GET:weixinGetMediaUrl parameters:param progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        UIImage *photo = [UIImage imageWithData:responseObject];
        if ([dict[@"type"] isEqualToString:@"image"]) {//图片
            message.photo = photo;
            cwqXHMessage.photo = photo;
            

        }else if ([dict[@"type"] isEqualToString:@"voice"]){//语音
            
        }else{//视频
            
        }
        [weakSelf.messageTableView reloadData];
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
    }];

    
}



#pragma mark -发送多媒体到 后台
- (void)sendToWeixinWithMessage:(XHMessage *)message indexPath:(NSIndexPath *)indexPath{
    
    static int i = 0;
    NSLog(@"多媒体-------------%d",i ++);
    NSDictionary *param;
    NSString *url;
    defineWeakSelf;
//    XHBubbleMessageMediaTypeText = 0,
//    XHBubbleMessageMediaTypePhoto = 1,
//    XHBubbleMessageMediaTypeVideo = 2,
//    XHBubbleMessageMediaTypeVoice = 3,
    
    switch (message.messageMediaType) {
        case 0:
            return;
    
            break;
        case 1:
            param = @{@"type":@"image"};
            url =weixinMessageUrl;

            break;
        case 2:
            param = @{@"type":@"video"};
          
             url =weixinMessageUrl;
            break;
        case 3:
            param = @{@"type":@"voice"};
            url =weixinMessageUrl;
            break;
        case 4:
//            param = @{@"access_token":accessToken,
//                      @"type":@"video"};
            break;
        case 5:
            //            [messages addObject:[self getGeolocationsMessage:me]];
            break;
            
        default:
            break;
    }
    
//    CWQIMNetManager IMPOST:url parameters:param message:<#(XHMessage *)#> prog<#^(NSString *)failure#>ress:<#^(CGFloat)uploadPercent#> success:<#^(id)success#> failure:
    
    [CWQIMNetManager IMPOST:url parameters:param message:message progress:^(CGFloat percent) {
        XHMessageTableViewCell *cell = [weakSelf.messageTableView cellForRowAtIndexPath:indexPath];
        cell.messageBubbleView.hud.progress = percent;
        
    } success:^(id result) {
       
        static int i = 0;
        NSLog(@"blcokzhixin-------------%d",i ++);
        if ([result isKindOfClass:[NSString class]]) {
            //非视频 mediaId
            [[WSJObserveNewChatTool sharedObserveTool] sendAmessageToServerWithMessage:message mediaId:result thumbMediaId:nil complelte:^(id responseObject) {
                message.completedSend = YES;
                //            [self deleteMessageInDatabaseWith:message];
                
                
                message.isSending = NO;
                message.conversionId = self.conversion.rowid;
                [weakSelf.messageTableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
                
                [message saveToDB];
            } fail:^(id errmesg) {
                message.completedSend = NO;
                message.isSending = NO;
               [weakSelf.messageTableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
                
            }];
            
        }else{
            NSArray *arr =result;
            //视频的时候 返回的是数组
            [[WSJObserveNewChatTool sharedObserveTool] sendAmessageToServerWithMessage:message mediaId:arr[0] thumbMediaId:arr[1] complelte:^(id responseObject) {
                message.completedSend = YES;
                //            [self deleteMessageInDatabaseWith:message];
                
                
                message.isSending = NO;
                message.conversionId = self.conversion.rowid;
                [weakSelf.messageTableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
                
                [message saveToDB];
            } fail:^(id errmesg) {
                message.completedSend = NO;
                message.isSending = NO;
                [weakSelf.messageTableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
                
            }];
            
          
        }
        
       
        
    } failure:^(NSString *msg) {
        message.completedSend = NO;
        message.isSending = NO;
        [message deleteToDB];
        [weakSelf.messageTableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
    }];

    
    
}







#pragma mark -对消息数据库 处理

- (void)deleteMessageInDatabaseWith:(XHMessage *)message {
    
    [message deleteToDB];
//    NSFetchRequest *request = [[NSFetchRequest alloc] init];
//    request.entity = [NSEntityDescription entityForName:@"CWQXHMessage" inManagedObjectContext:[WCCoreDataStore shareStore].context];
//    
//    NSPredicate *p1 = [NSPredicate
//                       predicateWithFormat:@"(conversation = %@)", [self.chaterInfo objectID]];
//    NSPredicate *p2 = [NSPredicate predicateWithFormat:@"(timestamp = %@)",
//                       message.timestamp];
//    NSPredicate *predicate = [NSCompoundPredicate andPredicateWithSubpredicates:@[p1, p2]];
//    [request setPredicate:predicate];
//    NSError *error;
//    NSArray *result = [[WCCoreDataStore shareStore].context executeFetchRequest:request error:&error];
//    if (result) {
//        
//        CWQXHMessage *cwqMessage = result[0];
//        [[WCCoreDataStore shareStore].context deleteObject:cwqMessage];
//    }
//


}


/**
 *  是否显示时间轴Label的回调方法
 *
 *  @param indexPath 目标消息的位置IndexPath  每个cell 多次调用
 *
 *  @return 根据indexPath获取消息的Model的对象，从而判断返回YES or NO来控制是否显示时间轴Label
 */
- (BOOL)shouldDisplayTimestampForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    
    return YES;
    
//    XHMessage *message  =self.messages[indexPath.row];
//    
//    if (!lastMessageDate) {
//       
//        return YES;
//    }
//    
//    NSTimeInterval f =  [lastMessageDate timeIntervalSinceDate:message.timestamp];
//    
//    if (f > 5 * 60) {
//        return YES;
//    }else{
//        return NO;
//    }
    
}

/**
 *  配置Cell的样式或者字体
 *
 *  @param cell      目标Cell
 *  @param indexPath 目标Cell所在位置IndexPath
 */
- (void)configureCell:(XHMessageTableViewCell *)cell atIndexPath:(NSIndexPath *)indexPath {
    
    

}

/**
 *  协议回掉是否支持用户手动滚动
 *
 *  @return 返回YES or NO
 */
- (BOOL)shouldPreventScrollToBottomWhileUserScrolling {
    return YES;
}

@end
